﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NPOI.OpenXmlFormats;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Bcpg.Sig;
using Quartz.Util;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using SyncService.Core.Utils;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Data;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "mutiTransfer")]
    public class MutiTransferSerive : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<ZeroResultSerive> _logger = null;
        private Dictionary<string, string> companyData = new Dictionary<string, string>();
        private Dictionary<string, string> centerData = new Dictionary<string, string>();
        private Dictionary<string, string> centerDatabyID = new Dictionary<string, string>();
        public MutiTransferSerive() : base(YdConstants.YIDEA, "Sap", "")
        {
        }
        protected override void InitializeContext()
        {
            base.SetMultiCallback();
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<ZeroResultSerive>>();
        }
        private List<Asset> assets = new List<Asset>();
        List<Asset> commonCompanyAsset = new List<Asset>();
        List<Asset> crossCompanyAsset = new List<Asset>();
        DataTable errorAsset = new DataTable();
        DataTable dataTable = new DataTable();
        Dictionary<string, int> barcodeInRow = new Dictionary<string, int>();
        public override void ExecuteCore()
        {
            var company = UserDefines.First(x => x.Name == "公司主数据");
            var center = UserDefines.First(x => x.Name == "成本中心");
            var companyNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
            var centerNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");

            var shopCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var shopNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");

            var assetComapnyField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司名称"));
            var assetCenterField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心名称"));


            var centerCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心码"));
            var companyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司代码"));
            var isGuoZhangField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "是否过账");
            var addressField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "存放地");

            var outCompanyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调出公司代码");
            var inCompanyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调入公司代码");
            var transferDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调拨时间");
            AssetSyncEvent Data = (AssetSyncEvent)State!;
            var serialNo = Data.Data["SerialNo"].ToString();
            var form = UserDefines.First(e => e.Name == "批量调拨单");
            var fileUploadField = ExtendFields.Where(e => e.ObjectType == 59 && e.Name == "附件").FirstOrDefault();
            var fileDemain = ExtendFields.Where(e => e.ObjectType == 0 && e.Name == "附件域名").FirstOrDefault();
            var filePath = fileDemain.FieldId + Data.Data[fileUploadField.FieldId]?[0]["url"].ToString();
            dataTable = Common.Excel.ReadExcel.ReadNetWorkFile(filePath);
            if (dataTable == null) {
                _logger.LogInformation("批量调拨单" + serialNo + "获取数据失败");
                return;
            }
            DataColumn workCol = dataTable.Columns.Add("失败原因", typeof(string));
            errorAsset = dataTable.Copy();
            errorAsset.Rows.Clear();
            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

            List<District> districts = YideaClient.GetDistricts(null).ToList();
            var companyList = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam() { }).ToList();
            ConvertCompanyToDic(companyList);
            var centerlist = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam() { }).ToList();
            ConvertCenterToDic(centerlist);
            List<Department> departmentList = YideaClient.GetDepartments(null).ToList();
           // List<Employee> employeeList = YideaClient.GetEmployees(null).ToList();

           List<string> barcodeList = new List<string>();
            for ( int i = 0; i < dataTable.Rows.Count; i++)
            {
                var row = dataTable.Rows[i];
                var barcode = row[0].ToString();
                barcodeList.Add(barcode);
            }




            #region    取所有资产
            var page = 0;
            var perPage = 100;
            var getAssetsBarcodes = barcodeList.Select(e => e).Skip(page * perPage).Take(perPage).ToList();
            while (getAssetsBarcodes.Any())
            {
                var yideaExistingAssetsRes = YideaClient.GetAssets(new QueryParam
                {
                    FilterString = $"orderby=-id&requireHierarchies=1&filterByPermission=1&barcodeIn={string.Join(",", getAssetsBarcodes)}"
                });
                var list = yideaExistingAssetsRes.ToList();
                assets.AddRange(list);
                page++;
                getAssetsBarcodes = barcodeList.Select(e => e).Skip(page * perPage).Take(perPage).ToList();

            }
            #endregion

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var row = dataTable.Rows[i];
                try
                {

                    var barcode = row[0].ToString();

                    if (barcodeInRow.ContainsKey(barcode))
                    {
                        continue;
                    }
                    else
                    {
                        barcodeInRow.Add(barcode, i);
                    }
                    var asset = assets.Where(e => e.Barcode == barcode).FirstOrDefault();
                    if (asset == null)
                    {
                        row[11] = "该资产在台账中不存在";
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    var assetJson = JsonNode.Parse(asset.DataJson).AsObject();
                    if (asset.State != 2) {
                        row[11] = "该资产状态不允许调拨--" + asset.State;
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    if (assetJson[isGuoZhangField.FieldId].ToString() != "是") {
                        row[11] = "该资产是否过账为否，不允许调拨";
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    if (asset.IncludedInBill > 0) {
                        row[11] = "该资产被占用，不允许调拨";
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    var assetCompanyCode = assetJson[companyCodeField.FieldId].ToString();

                    var distrinct = row[1].ToString();
                    if (!string.IsNullOrEmpty(distrinct))
                    {
                        var districtID = districts.Where(e => e.Name == distrinct).FirstOrDefault();
                        if (districtID == null)
                        {
                            row[11] = "该资产区域填写错误";
                            errorAsset.ImportRow(row);
                            continue;
                        }
                        asset.DistrictCode = districtID.Code;
                        asset.DistrictId = districtID.Id;
                        asset.DistrictName = districtID.Name;
                    }
                    
                    var companyCode = row[2].ToString();
                    _logger.LogInformation(serialNo + ":2:" + companyCode);
                    string companyJson = "", incompanyCode = "";
                    if (!string.IsNullOrEmpty(companyCode))
                    {
                        _logger.LogInformation(serialNo + ":21");
                        companyData.TryGetValue(companyCode, out companyJson);
                        _logger.LogInformation(serialNo + ":22:"+ companyJson);
                        if (string.IsNullOrEmpty(companyJson))
                        {
                            row[11] = "该资产公司代码填写错误";
                            errorAsset.ImportRow(row);
                            continue;
                        }
                        _logger.LogInformation(serialNo + ":23:");
                        var companyJsonData = JsonNode.Parse(companyJson).AsObject();
                        var companyDetail = JsonNode.Parse(companyJsonData["dataJson"].ToString()).AsObject();
                        _logger.LogInformation(serialNo + ":24:");
                        incompanyCode = companyCode;
                        assetJson[companyCodeField.FieldId] = companyCode;
                        assetJson[assetComapnyField.FieldId] = companyDetail[companyMasterNameField.FieldId].ToString();
                        companyJsonData.Remove("dataJson");
                        assetJson[assetComapnyField.FieldId] = companyJsonData;
                    }

                    var centerCode = row[3].ToString();
                    _logger.LogInformation(serialNo + ":3:"+ centerCode);
                    var centerJson = "";
                    if (!string.IsNullOrEmpty(centerCode))
                    {
                        centerData.TryGetValue(centerCode, out centerJson);
                        if (string.IsNullOrEmpty(centerJson))
                        {
                            row[11] = "该资产成本中心填写错误";
                            errorAsset.ImportRow(row);
                            continue;
                        }
                        _logger.LogInformation(serialNo + ":31:" + centerJson);
                        var centerDataJson = JsonNode.Parse(centerJson).AsObject();
                        var centerDetail= JsonNode.Parse(centerDataJson["dataJson"].ToString()).AsObject();
                        var centerName = centerDetail[centerMasterNameField.FieldId].ToString();
                        assetJson[centerCodeField.FieldId] = centerCode;
                        assetJson[centerNameField.FieldId] = (centerName.ToString());
                        centerData.Remove("dataJson");
                        assetJson[assetCenterField.FieldId] = centerDataJson;
                    }

                    var shopCode = row[4].ToString();
                    _logger.LogInformation(serialNo + ":4:" + shopCode);
                    var shopJson = "";
                    if (!string.IsNullOrEmpty(shopCode))
                    {
                        centerData.TryGetValue(shopCode, out shopJson);
                        if (string.IsNullOrEmpty(shopJson))
                        {
                            row[11] = "该资产店铺代码填写错误";
                            errorAsset.ImportRow(row);
                            continue;
                        }
                        _logger.LogInformation(serialNo + ":41:" + shopJson);
                        var centerDataJson = JsonNode.Parse(shopJson).AsObject();
                        var shopdetail= JsonNode.Parse(centerDataJson["dataJson"].ToString()).AsObject();
                        var centerName = shopdetail[centerMasterNameField.FieldId].ToString();
                        string centerId = "";
                        centerDatabyID.TryGetValue(centerCode, out centerId);

                        assetJson[shopCodeField.FieldId] = new JsonObject() {
                            ["value"] = centerId,
                            ["label"] = centerCode,
                            ["color"] = new JsonObject() {
                                ["backgroundColor"] = "#577eff",
                                ["foreColor"] = "#ffffff"
                            }
                        };
                        assetJson[shopNameField.FieldId] = centerName;
                    }

                    var address = row[5].ToString();
                    if (!string.IsNullOrEmpty(address)) {
                        assetJson[addressField.FieldId] = address;
                    }

                    var employeeName = row[6].ToString();
                    var employeeCode = row[7].ToString();
                    _logger.LogInformation(serialNo + ":6:" + employeeName + ":employeeName" + employeeCode);
                    if (!string.IsNullOrEmpty(employeeCode))
                    {
                        var employee = YideaClient.GetEmployee(employeeCode,""); //employeeList.Where(e => e.EmployeeNo == employeeCode).FirstOrDefault();
                        if (employee == null)
                        {
                            row[11] = "该资产使用人编码填写错误";
                            errorAsset.ImportRow(row);
                            continue;
                        }
                        _logger.LogInformation(serialNo + ":61:" + employee.DepartmentCode);
                        var department = departmentList.Where(e => e.Code == employee.DepartmentCode).FirstOrDefault();
                        _logger.LogInformation(serialNo + ":62:" + JsonSerializer.Serialize(department));
                        asset.UserEmployeeNo = employee.EmployeeNo;
                        asset.UserEmployeeName = employee.Name;
                        asset.UserEmployeeId = employee.Id.ToString();
                        if (department != null)
                        {
                            asset.UseDepartmentId = int.Parse(department.Id.ToString());
                            asset.UseDepartmentCode = department.Code;
                            asset.UseDepartmentName = department.Name;
                        }
                    }
                    //else
                    //{
                    //    asset.UseDepartmentCode = "";
                    //    asset.UseDepartmentId = 0;
                    //    asset.UseDepartmentName = "";
                    //    asset.UserEmployeeId = "";
                    //    asset.UserEmployeeName = "";
                    //    asset.UserEmployeeNo = "";
                    //}
                    assetJson[outCompanyCodeField.FieldId] = assetCompanyCode;
                    assetJson[inCompanyCodeField.FieldId] = incompanyCode;
                    assetJson[transferDateField.FieldId] = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    asset.DataJson = JsonSerializer.Serialize(assetJson);
                    if (!IsPush(asset.AssetTypeCode))
                    {
                        //row[11] = "该资产资产类别不符合推送sap要求";
                        //errorAsset.ImportRow(row);
                        //continue;
                        try
                        {
                            YideaClient.UpdateAsset(asset, asset);
                            if (!string.IsNullOrEmpty(asset.ErrorMessage))
                            {
                                row[11] = asset.ErrorMessage;
                                errorAsset.ImportRow(row);
                                break;
                            }
                            
                        }
                        catch (Exception ex) {
                                row[11] = ex.ToString();
                                errorAsset.ImportRow(row);
                                break;
                            
                        }
                        continue;
                    }
                    
                    var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                    if (string.IsNullOrEmpty(assetJson[facodeField.FieldId].ToString())) {
                        row[11] = "该资产没有sap财务编码";
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    if (assetCompanyCode == incompanyCode) //同公司调拨
                    {
                        _logger.LogInformation(serialNo + "步骤7");
                        commonCompanyAsset.Add(new Asset()
                        {
                            Barcode = asset.Barcode,
                            Name = asset.Name,
                            Specs = asset.Specs,
                            OwnCompanyCode = incompanyCode,
                            ExtraData = new JsonObject()
                            {
                                ["FACode"] = assetJson[facodeField.FieldId].ToString(),
                                ["CenterCode"] = assetJson[centerCodeField.FieldId].ToString()
                            }
                        });
                    }
                    else
                    {
                        _logger.LogInformation(serialNo + "步骤8");
                        //跨公司调拨
                        crossCompanyAsset.Add(new Asset()
                        {
                            Barcode = asset.Barcode,
                            Name = asset.Name,
                            Specs = asset.Specs,
                            AssetTypeCode = GetTopAssetTypeCode(asset.AssetTypeCode),
                            ExtraData = new JsonObject()
                            {
                                ["FACode"] = assetJson[facodeField.FieldId].ToString(),
                                ["CenterCode"] = assetJson[centerCodeField.FieldId].ToString(),
                                ["OutCompanyCode"] = assetCompanyCode,
                                ["InCompanyCode"] = incompanyCode
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogInformation(serialNo+"发生异常："+ex);
                    row[11] = "发生异常：" + ex.ToString();
                    errorAsset.ImportRow(row);
                    continue;

                }
            }

            if (commonCompanyAsset.Count > 0)
            {
                Transfer transfer = new Transfer();
                transfer.InCompanyCode = "A";
                transfer.OutCompanyCode = "A";

                transfer.ExtraData = new JsonObject
                {
                    ["type"] = "mutiTrans",
                    ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                    ["Memo"] = "",
                    ["ZDJBH"]= Data.Data["SerialNo"]!.ToString()

                };
                transfer.Assets = commonCompanyAsset;
                ToClient.AddNewTransfer(transfer);
            }
            if (crossCompanyAsset.Count > 0)
            {
                Transfer transfer = new Transfer();
                transfer.InCompanyCode = "A";
                transfer.OutCompanyCode = "B";

                transfer.ExtraData = new JsonObject
                {
                    ["type"] = "mutiTrans",
                    ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                    ["Memo"] = "",
                    ["ZDJBH"] = Data.Data["SerialNo"]!.ToString()
                };
                transfer.Assets = crossCompanyAsset;
                ToClient.AddNewTransfer(transfer);
            }
            string fullFile = "";
            if (errorAsset.Rows.Count > 0)
            {
                var filepath = ExportToString(errorAsset);
                var domainNameField = ExtendFields.First(e => e.Name == "域名" && e.ObjectType == 0);
                fullFile = filepath == "" ? "" : domainNameField.FieldId + filepath;

            }
            int flag = 0;
            if (commonCompanyAsset.Count > 0 || crossCompanyAsset.Count > 0)
            {
                flag = 1;
            }
            WriteToForm(Data.Data["SerialNo"]!.ToString(), fullFile,flag>0?"调用成功":"没有资产可调用" );
        }

        private void WriteToForm(string serialNo,string filePath,string sapResult) {
            _logger.LogInformation("批量调拨回写："+serialNo);
            var form = UserDefines.Where(e => e.Name == "批量调拨单").FirstOrDefault();
            var errorLinkField = ExtendFields.Where(e => e.Name == "错误数据链接" && e.ObjectType == 59).FirstOrDefault();
            var resultField = ExtendFields.Where(e => e.Name == "调拨结果" && e.ObjectType == 59).FirstOrDefault();
            var field = ExtendFields.First(x => x.ObjectType == 59 && x.Name == "sap单据状态");
            var searchArray = new JsonArray();
            searchArray.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = serialNo
            });
           
            var searchStr = JsonSerializer.Serialize(searchArray);
            var tj = YideaClient.GetUserDefinedForms(form.Id, new QueryParam() { FilterString = searchStr });
            if (tj.Count() > 0) {
                var result = "成功";
                if (!string.IsNullOrEmpty(filePath)) {
                    result = "失败";
                }
                var tjList = tj.ToList()[0];
                CustomizedFormData updateCustomer = new CustomizedFormData();
                updateCustomer.FormId = form.Id;
                updateCustomer.WebhookPush = false;
                updateCustomer.SerialNo = tjList.SerialNo;
                JsonObject upField = new JsonObject();
                upField[errorLinkField.FieldId] = new JsonObject
                {
                    ["value"] = filePath
                };
                upField[field.FieldId] = new JsonObject()
                {
                    ["value"] = sapResult
                };
                upField[resultField.FieldId] = new JsonObject()
                {
                    ["value"] = result
                };
                updateCustomer.Data = upField;
                var updateResponse1 = YideaClient.UpdateCustomizedFormData(updateCustomer, null);
                _logger.LogInformation("批量调拨回写：" + serialNo+"结果："+ updateResponse1);
            }
        }
        public override void CallbackHander(CallbackData data)
        {
            var sapCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
            _logger.LogInformation("单条回写"+JsonSerializer.Serialize(data));
            switch (data.Data) {
                case "-1"://跨公司调拨全部失败
                    foreach (var item in crossCompanyAsset)
                    {
                        var barcodeCross = item.Barcode;
                        int rowIndexCross = 0;
                        barcodeInRow.TryGetValue(barcodeCross, out rowIndexCross);
                        if (rowIndexCross > 0) {
                            var row = dataTable.Rows[rowIndexCross];
                            row[11] = data.ExtraData["message"].ToString();
                            errorAsset.Rows.Add(row);
                            break;
                        }
                    }
                    break;
                case "S"://调拨成功，更新资产
                    Asset asset= assets.Where(e=>e.Barcode==data.DataKey).FirstOrDefault();
                    if (asset != null) {
                        try
                        {
                            var sapCode = data.ExtraData["sapCode"]?.ToString();
                            if (!string.IsNullOrEmpty(sapCode)) {
                                var dataJson = JsonNode.Parse(asset.DataJson).AsObject();
                                dataJson[sapCodeField.FieldId] = sapCode;
                            }
                            YideaClient.UpdateAsset(asset, asset);
                        }
                        catch (Exception ex) {
                            asset.ErrorMessage = ex.ToString();
                        }
                        if (!string.IsNullOrEmpty(asset.ErrorMessage))
                        {
                            int index = -1;
                            if (barcodeInRow.ContainsKey(data.DataKey))
                            {
                                index = barcodeInRow[data.DataKey];
                            }

                            if (index > -1)
                            {
                                var row = dataTable.Rows[index];
                                row[11] = asset.ErrorMessage;
                                errorAsset.ImportRow(row);
                                break;
                            }
                        }
                    }
                    break;
                default: //调拨失败，放失败日志
                    var barcode = data.DataKey;
                    int rowIndex = -1;
                    if (barcodeInRow.ContainsKey(barcode)) {
                        rowIndex = barcodeInRow[barcode];
                    }
                    
                    if (rowIndex > -1)
                    {
                        var row = dataTable.Rows[rowIndex];
                        row[11] = data.ExtraData["message"].ToString();
                        errorAsset.ImportRow(row);
                        break;
                    }
                    break;
            }
          
        }
        private bool IsPush(string assetTypeCode)
        {
            string NotPushSap = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "NotPushAssetType").FieldId;
            var code = GetTopAssetTypeCode(assetTypeCode);
            _logger.LogInformation("推送sap资产编码是否推送：" + NotPushSap.Contains("," + code + ","));
            return NotPushSap.Contains("," + code + ",");
        }
        private string GetTopAssetTypeCode(string assetTypeCode)
        {
            List<AssetType> assetTypeList = GetAssetTypeFromCache();
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchyId = assetType.Hierarchy.Split('|')[0];
            int topAssetTypeId = 0;
            int.TryParse(hierarchyId, out topAssetTypeId);
            var topAssetType = assetTypeList.Where(e => e.Id == topAssetTypeId).FirstOrDefault();
            if (topAssetType != null)
            {
                return topAssetType.Code;
            }
            else
            {
                return assetTypeCode;
            }
        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        private void ConvertCompanyToDic(List<CustomizedFormData> datas)
        {
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[companyMasterCodeField.FieldId].ToString();
                if (companyData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    companyData.Add(key, custmerData);
                }
            }
        }
        private void ConvertCenterToDic(List<CustomizedFormData> datas)
        {
            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[centerMasterCodeField.FieldId].ToString();
                if (centerData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    centerData.Add(key, custmerData);
                }
                //var code = companyDataJson[centerMasterCodeField.FieldId].ToString();
                if (centerDatabyID.ContainsKey(key))
                {
                    continue;
                }
                else {
                    centerDatabyID.Add(key, data.Id.ToString());
                }
                
            }
        }
        public string ExportToString(DataTable dataTable)
        {
            _logger.LogInformation("开始导出资产回写情况统计excel~");
            var template = Path.Combine(SyncService.Common.Constants.WebRootPath, "Templates", "批量调拨回写统计.xlsx");
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "temp", $"{fileName}批量调拨回写统计.xlsx");
            string directory = Path.GetDirectoryName(target);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            System.IO.File.Copy(template, target);
            FileStream file = new FileStream(target, FileMode.Open, FileAccess.Read);
            var workbook = new XSSFWorkbook(file);
            var sheet = workbook.GetSheet("批量调拨回写统计");
            int rowIndex = sheet.LastRowNum ;

           for(int i = 0; i < dataTable.Rows.Count; i++) { 
                var row= dataTable.Rows[i];
                XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                dataRow.CreateCell(0).SetCellValue(row[0].ToString());
                dataRow.CreateCell(1).SetCellValue(row[1].ToString());
                dataRow.CreateCell(2).SetCellValue(row[2].ToString());
                dataRow.CreateCell(3).SetCellValue(row[3].ToString());

                dataRow.CreateCell(4).SetCellValue(row[4].ToString());
                dataRow.CreateCell(5).SetCellValue(row[5].ToString());
                dataRow.CreateCell(6).SetCellValue(row[6].ToString());
                dataRow.CreateCell(7).SetCellValue(row[7].ToString());
                dataRow.CreateCell(8).SetCellValue(row[11].ToString());
                ++rowIndex;
            }

            using (var stream = new FileStream(target, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }
            _logger.LogInformation("生成excel");
            _logger.LogInformation(target);
            //string base64 = FileToBase64String.FileToBase64(target);
            return "/temp/" + fileName + "批量调拨回写统计.xlsx";
        }
    }
}
